package com.example.audiostreaming.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiostreaming.Bean.UserBean;
import com.example.audiostreaming.R;
import com.example.audiostreaming.adapters.AdapterMagicIndicator;
import com.example.audiostreaming.adapters.AdapterMainViewPager;
import com.example.audiostreaming.base.BaseActivity;
import com.example.audiostreaming.data.XimalayaDBHelper;
import com.example.audiostreaming.implement.ImplPlayerLogic;
import com.example.audiostreaming.implement.ImplRecommendLogic;
import com.example.audiostreaming.interfaces.IPlayerViewCallback;
import com.example.audiostreaming.utils.UtilLog;
import com.example.audiostreaming.views.ViewCircleImageView;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.List;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    private MagicIndicator mMagicIndicator;//魔术指示器
    private ViewPager mMainViewPager;//主视图页面
    private AdapterMagicIndicator mAdapterMagicIndicator;////魔术指示器的适配器
    private ViewCircleImageView mMainTrackCover;
    private TextView mMainTrackTitle;
    private TextView mMainTrackAuthor;
    private ImageView mMainPlayControl;
    private ImplPlayerLogic mInstanceImplPlayerLogic;
    private PlayerViewCallback mPlayerViewCallback;
    private View mMainPlayItem;
    private ImageView mMainPlayNext;
    private View mSearchBtn;
    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//初始化视图
        initEvent();//初始化事件
        mInstanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
        mPlayerViewCallback = new PlayerViewCallback();
        mInstanceImplPlayerLogic.registerViewCallback(mPlayerViewCallback);

    }


    private void initView() {
        TextView userName = findViewById(R.id.user_name);
        userName.setText(UserBean.getUserBean().getName());

        mDrawerLayout = findViewById(R.id.drawer_layout);

        //一、MagicIndicator魔术指示器
        mMagicIndicator = findViewById(R.id.main_indicator);
        mMagicIndicator.setBackgroundColor(getResources().getColor(R.color.color_Main));
        //创建MagicIndicator魔术指示器的适配器
        mAdapterMagicIndicator = new AdapterMagicIndicator(this);
        CommonNavigator commonNavigator = new CommonNavigator(this);//通用导航器
        commonNavigator.setAdapter(mAdapterMagicIndicator);
        commonNavigator.setAdjustMode(true);//设置自动调整模式,自动平分导航器区域
        mMagicIndicator.setNavigator(commonNavigator);//设置导航器


        //二、MainViewPager主视图页面
        mMainViewPager = findViewById(R.id.main_viewpager);
        //创建MainViewPager视图页面的适配器
        FragmentManager supportFragmentManager = getSupportFragmentManager();//片段管理器
        AdapterMainViewPager adapterMainViewPager = new AdapterMainViewPager(supportFragmentManager);
        mMainViewPager.setAdapter(adapterMainViewPager);


        //三、将MagicIndicator魔术指示器与MainViewPager主视图页面绑定到一起
        ViewPagerHelper.bind(mMagicIndicator, mMainViewPager);


        //主界面播放控制相关
        mMainTrackCover = findViewById(R.id.main_track_cover);
        mMainTrackTitle = findViewById(R.id.main_track_title);
        mMainTrackTitle.setSelected(true);
        mMainTrackAuthor = findViewById(R.id.main_track_author);
        mMainPlayControl = findViewById(R.id.main_play_control);
        mMainPlayNext = findViewById(R.id.main_play_next);
        mMainPlayItem = findViewById(R.id.main_play_item);

        mSearchBtn = findViewById(R.id.search_btn);
    }

    private void initEvent() {
        mAdapterMagicIndicator.setOnMagicIndicatorTabClickListener(new AdapterMagicIndicator.OnMagicIndicatorTabClickListener() {
            @Override
            public void onMagicIndicatorTabClick(int index) {
                UtilLog.d(TAG, "点击索引是 ==> " + index);
                //改变MainViewPager主视图页面的显示页面
                if (mMainViewPager != null) {
                    mMainViewPager.setCurrentItem(index,false);//false，取消滑动动画
                }
            }
        });
        mMainPlayControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInstanceImplPlayerLogic != null) {
                    boolean hasPlayList = mInstanceImplPlayerLogic.hasPlayList();
                    if (!hasPlayList) {
                        //没有设置过播放列表，我们就播放默认的第一个推荐专辑
                        //第一个推荐专辑，每天都会变
                        playFirstRecommend();
                    }else {
                        if (mInstanceImplPlayerLogic.isPlaying()) {
                            mInstanceImplPlayerLogic.pause();
                        }else {
                            mInstanceImplPlayerLogic.play();
                        }
                    }

                }
            }
        });
        mMainPlayItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInstanceImplPlayerLogic != null) {
                    boolean hasPlayList = mInstanceImplPlayerLogic.hasPlayList();
                    if (!hasPlayList) {

                    }else {
                        startActivity(new Intent(MainActivity.this,PlayerActivity.class));
                    }
                }
            }
        });
        mMainPlayNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInstanceImplPlayerLogic != null) {
                    boolean hasPlayList = mInstanceImplPlayerLogic.hasPlayList();
                    if (!hasPlayList) {

                    }else {
                      mInstanceImplPlayerLogic.playNext();
                    }
                }
            }
        });

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 播放第一个推挤的内容
     */
    private void playFirstRecommend() {
        List<Album> currentRecommend = ImplRecommendLogic.getInstanceImplRecommendLogic().getCurrentRecommend();
        if (currentRecommend != null&& currentRecommend.size()>0) {
            Album album = currentRecommend.get(0);
            long albumId = album.getId();
            mInstanceImplPlayerLogic.playByAlbumId(albumId);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        XmPlayerManager.release();//播放器释放
        if (mInstanceImplPlayerLogic != null) {
            mInstanceImplPlayerLogic.unRegisterViewCallback(mPlayerViewCallback);
            mInstanceImplPlayerLogic = null;
        }
    }

    public void onToDrawerLayout(View view) {
        mDrawerLayout.openDrawer(GravityCompat.START);//打开侧滑界面
    }

    public void onToMeClick(View view) {
        Intent intent = new Intent(this, MeActivity.class);
        startActivity(intent);
    }


    private class PlayerViewCallback implements IPlayerViewCallback{
        @Override
        public void onPlayStart() {
            updatePlayControl(true);
        }
        private void updatePlayControl(boolean isPlaying){
            if (mMainPlayControl != null) {
                mMainPlayControl.setImageResource(isPlaying?R.drawable.selector_player_stop:R.drawable.selector_player_play);
            }
        }

        @Override
        public void onPlayPause() {
            updatePlayControl(false);
        }

        @Override
        public void onPlayStop() {
            updatePlayControl(false);
        }

        @Override
        public void onPlayError() {

        }

        @Override
        public void onPrePlay(Track track) {

        }

        @Override
        public void nextPlay(Track track) {

        }

        @Override
        public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

        }

        @Override
        public void onListLoaded(List<Track> list) {

        }

        @Override
        public void onProgressChange(int currPos, int duration) {

        }

        @Override
        public void onAdLoading() {

        }

        @Override
        public void onAdFinished() {

        }

        @Override
        public void onTrackUpdate(Track track, int playIndex) {
            if (track != null) {
                String trackTitle = track.getTrackTitle();
                String nickname = track.getAnnouncer().getNickname();
                String coverUrlMiddle = track.getCoverUrlMiddle();
                UtilLog.d(TAG,"标题 ==> "+trackTitle);
                UtilLog.d(TAG,"作者 ==> "+nickname);
                UtilLog.d(TAG,"图片 ==> "+coverUrlMiddle);
                if (mMainTrackTitle != null) {
                    mMainTrackTitle.setText(trackTitle);
                }
                if (mMainTrackAuthor != null) {
                    mMainTrackAuthor.setText(nickname);
                }
                if (mMainTrackCover != null) {
                    if (!TextUtils.isEmpty(coverUrlMiddle)) {
                        Picasso.with(MainActivity.this).load(coverUrlMiddle).into(mMainTrackCover);
                    }else {
                        mMainTrackCover.setImageResource(R.mipmap.logo_icon);
                    }
                }

            }
        }

        @Override
        public void updateListOrder(boolean isReverse) {

        }
    }
}
